package com.bonc.common.filter;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jinlong
 * @date 2021/8/3
 */
@Slf4j
@Component
@EnableConfigurationProperties(FilterProperties.class)
public class HostFilter implements Filter {

    @Resource
    private FilterProperties filterProperties;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String serverName = request.getServerName();
        if (StrUtil.isNotEmpty(serverName)) {
            if (checkBlankList(serverName)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                log.warn("[serverName deny access tips]->" + serverName);
                response.setStatus(403);
                response.flushBuffer();
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }


    /**
     * 校验当前host是否在白名单中
     */
    private boolean checkBlankList(String serverName) {
        for (String str : filterProperties.getAllowServerName()) {
            if (StrUtil.isNotEmpty(str) && str.equals(serverName)) {
                return true;
            }
        }
        return false;
    }

}
